<%@ include file="/WEB-INF/views/taglib.jsp" %>
<h3>Issue Order Form</h3>	
	<form:form id="form" method="post" modelAttribute="assetTransaction"  cssClass="simpleForm">
		<form:hidden path="assetTransactionId" />
		<form:hidden path="accessDepartment.departmentId" />
		
		
	 <div class="action">
     
  	  	<c:choose>	  	
	  		<c:when test="${assetTransaction.assetTransactionId==null}">
	  			<button type="button" class="button positive" onclick="formSubmit()">
	  			Save
	  			</button>
	  			<a href="<c:url value="/issueOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${assetTransaction.assetTransactionId!=null}">
  				<a href="<c:url value="/issueOrder/print/${assetTransaction.assetTransactionId}/COMPONENT" />" target='_blank' class="button">Print</a> 	  			
  				<a href="<c:url value="/issueOrder/search" />" class="button">Back</a>
	  		</c:when>
	  	</c:choose>
	 </div>	
	 <div class="clear" style="height:1px">&nbsp;</div>
	 <jsp:include page="/WEB-INF/views/message.jsp"></jsp:include>
	  	<fieldset>
	  		<legend>Issue Order Info</legend>
	  		<div class="span-12">
	  		<aims:column cssErrorClass="error" path="assetTransactionType" >
	  		<label>
	  			Issue Order Type  * 
	 		</label>
	  		<form:select id="assetTransactionType" path="assetTransactionType" onchange="redirectAssetTransactionType(this.value)">
	  			<form:option value="IO">Issue Component</form:option>
	  			<form:option value="ET">Equipment Transfer</form:option>
	  			<form:option value="FT">Faulty Equipment Transfer</form:option>
	  			<form:option value="SOI">Sales</form:option>
	  			<form:option value="INH">In-House Repair</form:option>
	  		</form:select>
	  		<form:errors path="assetTransactionType"  cssClass="errorSimple" /> 
			</aims:column>
			<aims:column cssErrorClass="error" path="fromLocation.locationId" >
	  		<label>
	  			From Location
	 		</label>
	 		
	 		<c:choose>
	 			<c:when test="${empty assetTransaction.assetTransactionCode}">
	 				<form:select path="fromLocation.locationId" id="fromLocationId">
			  			<form:options items="${fromLocations}" itemLabel="locationName" itemValue="locationId" />
			  		</form:select>
	 			</c:when>
	 			<c:otherwise>
	 				${assetTransaction.fromLocation.locationName}
	 				<form:hidden path="fromLocation.locationId" id="fromLocationId" />
	 			</c:otherwise>
	 		</c:choose>
	 		
	 		
			
	  		<form:errors path="fromLocation.locationId"  cssClass="errorSimple" /> 
			</aims:column>
			<aims:column cssErrorClass="error" path="toLocation.locationId" >
	  		<label>
	  			To Location
	 		</label>
	 		
	 		<c:choose>
	 			<c:when test="${empty assetTransaction.assetTransactionCode}">
	 				<form:select path="toLocation.locationId" id="toLocationId">
			  			<form:options items="${toLocations}" itemLabel="locationName" itemValue="locationId" />
			  		</form:select>
	 			</c:when>
	 			<c:otherwise>
	 				${assetTransaction.toLocation.locationName}
	 				<form:hidden path="toLocation.locationId" />
	 			</c:otherwise>
	 		</c:choose>
			
	  		<form:errors path="toLocation.locationId"  cssClass="errorSimple" /> 
			</aims:column>
			<aims:column cssErrorClass="error" path="companyCode">
		  		<form:label path="companyCode">
		  			Company Code
		 		</form:label>	
		 		<form:select id="companyCode" path="companyCode" class="companyCode">
		 			<form:options items="${globalCompanyCode}" itemValue="systemCode1" itemLabel="systemCodeValueDescription" />
		 		</form:select>
		  		 <form:errors path="companyCode"  cssClass="errorSimple" />	 
			</aims:column>	
			</div>
			<div class="span-8">
			<aims:column cssErrorClass="error" path="assetTransactionCode"  cssClass="clearfix">
	  		<label>
	  			Issue Order Code  
	 		</label>
	  			${assetTransaction.assetTransactionCode } 
			</aims:column>
			<aims:column cssErrorClass="error" path="assetTransactionCode" cssClass="clearfix">
	  		<label>
	  			Issue Order Date  
	 		</label>
	 			<fmt:formatDate value="${assetTransaction.approvedDate}" pattern="${globalDateFormatJava}"/>
	  			 
			</aims:column>
			<aims:column cssErrorClass="error" path="assetTransactionStatus" cssClass="clearfix">
	  		<label>
	  			Issue Order Status
	 		</label>
	 			${assetTransaction.assetTransactionStatus} 
			</aims:column>
			
			  			
			</div>
			</fieldset>
			<fieldset>
			<legend>Asset Info</legend>
			
			<c:if test="${empty assetTransaction.assetTransactionId}">
			<div class="span-8 minLabel"> 
	  		<p class="clearfix">
	  		<label> Asset Model</label>
		  	<select name="assetModelId" id="assetModelId" class="assetModelId">
		  	</select>	
		  	</p>
		  	<p class="clearfix">
		  	<label>Quantity </label> 
	  		<input name="quantity" id= "quantity" type="text" size="5" />
	  		</p>
	  		<p class="clearfix">
	  				  		
	  		<a onclick="addRow()" class="button">+ Add to list</a>	
	  		<sec:authorize access="authenticated and ( hasRole('ACCESS_COMPONENT_SEARCH') or hasRole('ACCESS_SUPER_ADMIN') or hasRole('ACCESS_MASTER')) ">  		
	  		<a onclick="popUp()" class="button">Available Stock</a>
	  		</sec:authorize>
	  		 	  		
	  		</p>	
			</div>
			</c:if>
			
			<c:choose>
				<c:when test="${empty assetTransaction.assetTransactionId}">
				<div class="span-14 last">
				</c:when>
				<c:otherwise>
				<div class="last">
				</c:otherwise>
			</c:choose>
		  	
	  		<table id="componentTable" class="gridSearch">
	  			<caption id="header" class="captionLeft">Total number of items : 
		  		<span id="totalItems"></span></caption>
	  			<thead>
	  				<tr>
	  					<c:if test="${assetTransaction.assetTransactionId==null}">
	  					<th>Remove</th>
	  					</c:if>
	  					<th>Asset Model</th>
	  					<th>Qty</th>
	  					<th>Remarks</th>
	  					
	  				</tr>
	  			</thead>
	  			<tbody>
	  			<c:choose>
	  				<c:when test="${assetTransaction.assetTransactionId==null}">
	  					<c:forEach items="${assetTransaction.assetTransactionItems}" var="item" varStatus="status">
			  				<tr <c:if test="${(status.count%2)==0 }">class="alt"</c:if>>
			  				<td>
			  				
			  				<input name="assetTransactionItems[${status.index}].deleted" type="hidden" class="deleted" value="${item.deleted}" />
			  					<input name="assetTransactionItems[${status.index}].assetModel.assetModelId" type="hidden" class="assetModelId" value='${item.assetModel.assetModelId}' />
			  					<input name="assetTransactionItems[${status.index}].assetModel.assetModelName" type="hidden" class="assetModelName" value='${item.assetModel.assetModelName}' />
			  					<a href="javascript:void(0)" onclick="removeRow(this)" title="Delete Row">
									<img align="absmiddle" src="${imageUrl}/icon_delete.png">
								</a>
			  				</td>
			  				<td>
			  					${item.assetModel.assetModelName}
			  				</td>
			  				<td>
			  					<input name="assetTransactionItems[${status.index}].assetTransactionQuantity" type="text" size="5" value="${item.assetTransactionQuantity}"
			  					class="assetTransactionQuantity"/>
			  				</td>
			  				<td>
			  					<textarea name="assetTransactionItems[${status.index}].remarks" rows="2" cols="20">${item.remarks}</textarea>
			  				</td>
			  				</tr>
			  			</c:forEach>	
	  				</c:when>
	  				<c:otherwise>
	  					<c:forEach items="${assetTransaction.assetTransactionItems}" var="item" varStatus="status">
			  				<tr <c:if test="${(status.count%2)==0 }">class="alt"</c:if>>
			  				<td>${item.assetModel.assetModelName}</td>
			  				<td>${item.assetTransactionQuantity}</td>
			  				<td>${item.remarks}</td>
			  				</tr>
			  			</c:forEach>	
	  				</c:otherwise>
	  			</c:choose>
	  			
	  			</tbody>
	  		</table>
	  
	  		</div>
	  		
			</fieldset>
			
      <div class="action">
     
  	  	<c:choose>	  	
	  		<c:when test="${assetTransaction.assetTransactionId==null}">
	  			<button type="button" class="button positive" onclick="formSubmit()">
	  			Save
	  			</button>
	  			<a href="<c:url value="/issueOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${assetTransaction.assetTransactionId!=null}">
  				<a href="<c:url value="/issueOrder/print/${assetTransaction.assetTransactionId}/COMPONENT" />" target='_blank' class="button">Print</a> 	  			
  				<a href="<c:url value="/issueOrder/search" />" class="button">Back</a>
	  		</c:when>
	  	</c:choose>
	 </div>	
	</form:form>
	
	<table id="tmpTable" style="visibility:hidden">
		<tr class="new">
		<td>
	  		<a href="javascript:void(0)" onclick="removeRow(this)" title="Delete Row">
				<img align="absmiddle" src="${imageUrl}/icon_delete.png">
			</a>
	  	</td>
		<td>
		<input name="assetTransactionItems.deleted" type="hidden"  class="deleted"/>
		<input name="assetTransactionItems.assetModel.assetModelId" type="hidden" class="assetModelId" />
		<input name="assetTransactionItems.assetModel.assetModelName" type="hidden" />
		<span class="assetModelName"></span>
	  	</td>
	  	<td>
	  	<input name="assetTransactionItems.assetTransactionQuantity" type="text" size="5" class="assetTransactionQuantity"/> 
	  	</td>
	  	<td>
	  	<textarea name="assetTransactionItems.remarks" rows="2" cols="20"></textarea>
	  	</td>
	  	
		</tr> 	
	</table>
	<script type="text/javascript">
		var finalValidRowCount = 0;
		var componentSet = new Array();		
		$(document).ready(function() {			
			$(".assetTransactionQuantity").numeric(false, function() { this.value = ""; this.focus(); });	
			$("#quantity").numeric(false, function() { this.value = ""; this.focus(); });		
			
			var assetModelComp;			
			$.getJSON("<c:url value="/ajax/asset/component"></c:url>", function(data) {
				
				assetModelComp = data;
				for(var i=0;i<assetModelComp.length;i++)
				{
					$('#assetModelId').
			          append($("<option></option>").
			          attr("value",assetModelComp[i].assetModelId).
			          attr("label",assetModelComp[i].assetModelName).
			          text(assetModelComp[i].assetModelName));
				}
			});
			
			<c:if test="${not empty assetTransaction.assetTransactionId}">
			$('#form').find('select').attr('disabled','disabled'); 
			</c:if>
			
			var ct = $('#componentTable tbody tr');
			if(ct){
			finalValidRowCount = ct.size();
			}
			hideHiddenRows();
			
			if(finalValidRowCount<=0){
				$('#header').hide();				
			}
			else{			
				$('#header').show();
				$('#totalItems').text(finalValidRowCount);
			}
		});
		
		function popUp(){
			var fromLocationName = $('#fromLocationId option:selected').text();
			var companyCode = $('#companyCode').val();
			var assetModelName = $('#assetModelId option:selected').text();
			
						
			var url="<c:url value="/assetModel/componentSearch"></c:url>?search['assetModel.assetModelName']="+assetModelName+ 
						"&search['location.locationName']="+fromLocationName+"&search['companyCode']="+companyCode+"&popUpFlag=Y";
			
			openPopUp(url);								
					
		}
		
		 function openPopUp(url)  
		 {  
		  newwindow = window.open(url,'_blank',"height=500,width=1100,resizable=yes,scrollbars=yes");  
		  newwindow.focus() ;
		 } 
		
		
		function redirect(form,url){
			form.attr('action',url );
			
			form.submit();
		}
		
		function formSubmit(){
			if(validateForm()){
			var url = "<c:url value="/issueOrder/create"/>";
			var form = $('#form');				
			redirect(form,url);
			}
		}
		
		function validateForm(){
			var res = true;			
			var table = $(' #componentTable tbody tr');		
			var quantityOrder;
			table.each(
					function (index) {
						
							if ( $(this).is(':visible') ) { 
						
										  quantityOrder = $('.assetTransactionQuantity',this).val();
										 if(quantityOrder == ''){
											 alert(" Pls do enter the quantity");
											 res = false;
											 return false;
										}
							}
					}					
			);
			
			var fromLocationId = $('#fromLocationId').val();
			var toLocationId = $('#toLocationId').val();
			
			
			if(fromLocationId == toLocationId)
			{
				alert(" From Location and To Location should not be equal ");
				res = false;
				return res;
			}
			
			if(finalValidRowCount == 0)
				{
				alert(" No valid record to start processing");
				res = false;
				return res;
				
				}
	
		return res;
	}
			
			
		
		
		function hideHiddenRows()
		{			
		var table = $(' #componentTable tbody tr');
			
			var hiddenRow=false;
			var modelId;
			table.each(
					function () {
						
					hiddenRow = $('.deleted',this).val();
					 modelId = $('.assetModelId',this).val();
					
					///alert(hiddenRow);
						if(hiddenRow=='true'){
							$(this).hide();
							finalValidRowCount--;
							removeInContain(componentSet,modelId);
						}
					}
					);
			
		}
		
		function checkContain(contain, obj)
		{
			if(contain && contain.length>0){
				for(var i=0;i<contain.length;i++){
					if(contain[i] == obj){
						return false;
					}
				}
			}
			contain.push(obj);
			return true;
		}
		
		function removeInContain(contain, obj)
		{
			if(contain && contain.length>0){
				for(var i=0;i<contain.length;i++){
					if(contain[i] == obj){
						contain.splice(i,1);
					}
				}
			}
		}
		
		
		function addRow()
		{
			var row = $('#tmpTable tr').clone();
			var rowSize = $('#componentTable tbody tr').size();
			
			var assetModelId = $('#assetModelId').val();
			var quantity = $('#quantity').val();
			
			var assetTransactionType = $("#assetTransactionType").val();
			var formLocation = $("#formLocation").val();
			

			if(checkContain(componentSet, assetModelId)){
				
				$('input[name=assetTransactionItems.assetModel.assetModelId]',row).attr('name','assetTransactionItems['+rowSize+'].assetModel.assetModelId').val(assetModelId);
				$('.assetModelName',row).text($('#assetModelId option:selected').text());
				$('input[name=assetTransactionItems.deleted]',row).attr('name','assetTransactionItems['+rowSize+'].deleted').val(false);
				$('input[name=assetTransactionItems.assetModel.assetModelName]',row).attr('name','assetTransactionItems['+rowSize+'].assetModel.assetModelName').val($('#assetModelId option:selected').text());		
				$('input[name=assetTransactionItems.assetTransactionQuantity]',row).attr('name','assetTransactionItems['+rowSize+'].assetTransactionQuantity').val(quantity);
				$('textarea[name=assetTransactionItems.remarks]',row).attr('name','assetTransactionItems['+rowSize+'].remarks');
		
				row.appendTo('#componentTable tbody');
				finalValidRowCount++;
				$('#totalItems').text(finalValidRowCount);
				$('#header').show();
				$(".assetTransactionQuantity").numeric(false, function() { this.value = ""; this.focus(); });	
			}else{
				alert("The Asset Component has already add.");
			}
		}
		
		function removeRow(obj)
		{
			var ctx = $(obj).parent().parent();
			var modelId = $('input[name*=assetModelId]',ctx).val();
			
				$('input[name*=deleted]',ctx).val('true');
				ctx.hide();
				finalValidRowCount--;
				$('#totalItems').text(finalValidRowCount);
				$('#header').show();
			
			
			removeInContain(componentSet,modelId);
		}
		
		function redirectAssetTransactionType(value)
		{
			if(value=='IO'){
				location.href='<c:url value="/issueOrder/create"></c:url>';
			}else if(value=='ET'){
				location.href='<c:url value="/issueOrder/createStockTransfer?assetTransactionType=ET"></c:url>';
			}			
			else if(value=='SOI'){
				location.href='<c:url value="/issueOrder/createStockTransfer?assetTransactionType=SOI"></c:url>';
			}			
			else if(value=='INH'){
				location.href='<c:url value="/issueOrder/createStockTransfer?assetTransactionType=INH"></c:url>';
			}
			else{
				location.href='<c:url value="/issueOrder/createStockTransfer?assetTransactionType=FT"></c:url>';
			}
		}
	</script>
	